/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package org.jackysoft.opensymphony.workflow.util;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jackysoft.entity.Step;
import org.jackysoft.entity.WorkflowEntry;
import org.jackysoft.opensymphony.workflow.Condition;
import org.jackysoft.opensymphony.workflow.StoreException;
import org.jackysoft.opensymphony.workflow.WorkflowContext;
import org.jackysoft.service.VariableService;
import org.jackysoft.service.WorkflowService;


/**
 * <p>
 * A simple utility condition that returns true if the the current user (caller)
 * is the step owner.
 * </p>
 * 
 * <p>
 * This condition may be used to deny the owner of the step by negating the
 * condition in the workflow descriptor with <code>negate='true'</code>.
 * <p>
 * 
 * <p>
 * Looks at ALL current steps unless a step id is given in the optional argument
 * "stepId".
 * </p>
 * 
 * <p>
 * The implementation was originally contained in AllowOwnerOfStepCondition by
 * Pat Lightbody.
 * </p>
 * 
 * @author <a href="mailto:plightbo@hotmail.com">Pat Lightbody </a> (original
 *         implementation)
 * @author <a href="mailto:adam@southtech.co.uk">Adam Southall </a> (refactored
 *         owner conditions to use this generic class.
 */
public class IsUserOwnerCondition implements Condition {
	// ~ Methods
	// ////////////////////////////////////////////////////////////////

	// ////////////////////////////////////////////////////////////////
	public boolean passesCondition(Map<String,Object> transientVars, Map<String,String> args,
			VariableService vservice) throws StoreException {
		int stepId = 0;
		String stepIdVal = (String) args.get("stepId");

		if (stepIdVal != null) {
			try {
				stepId = Integer.parseInt(stepIdVal);
			} catch (Exception ex) {
			}
		}

		WorkflowContext context = (WorkflowContext) transientVars
				.get("context");
		WorkflowEntry entry = (WorkflowEntry) transientVars.get("entry");
		WorkflowService store = (WorkflowService) transientVars.get("store");
		List currentSteps = store.findCurrentSteps(entry.getId());

		if (stepId == 0) {
			for (Iterator iterator = currentSteps.iterator(); iterator
					.hasNext();) {
				Step step = (Step) iterator.next();

				if ((step.getOwner() != null)
						&& context.getCaller().equals(step.getOwner())) {
					return true;
				}
			}
		} else {
			for (Iterator iterator = currentSteps.iterator(); iterator
					.hasNext();) {
				Step step = (Step) iterator.next();

				if (stepId == step.getStepId()) {
					if ((step.getOwner() != null)
							&& context.getCaller().equals(step.getOwner())) {
						return true;
					}
				}
			}
		}

		return false;
	}
}
